import React from 'react';
import { SecondHeaderC, ModalC, TableC, InputNumberC, PrimaryC, PrimaryGhostC, InfoTipsC } from '../../../../../comps';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Col, Row, DatePicker, Tooltip } from 'antd';
import uuid from 'es6-uuid';
import style from './index.less';
import { FormItemLayout } from '../../../../../comps/form/formPub';
import { connect } from 'dva';
import moment from 'moment';
const FormItem = Form.Item;
@Form.create()
class Redemption extends React.Component {
  static defaultProps = {
    onRef: () => {},
  };
  state = {
    rowData: {}, //当前编辑行的数据
    isShow: false, //是否显示弹窗
    showType: '1', // 1新增 2编辑
    fxData: [], //列表数组
  };
  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
    this.props.initInfo && this.props.initInfo.map((item) => (item.oldPayInterestAmount = item.payInterestAmount)); //保存初始利息金额
    this.setState({
      fxData: JSON.parse(JSON.stringify(this.props.initInfo || [])),
    });
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps.initInfo) != JSON.stringify(this.props.initInfo)) {
      nextProps.initInfo && nextProps.initInfo.map((item) => (item.oldPayInterestAmount = item.payInterestAmount)); //保存初始利息金额
      this.setState({
        fxData: JSON.parse(JSON.stringify(nextProps.initInfo || [])),
      });
    } else {
      //付息日程依赖的参数变化 则清空付息日程
      this.resetFxData(nextProps);
    }
  }
  //付息日程依赖的参数变化 则清空付息日程
  resetFxData = (nextPorps) => {
    //判断【金额】【付息频率】【计息基础】【起息日】【到期日】是否为空
    var arr = ['issueScale', 'interestRate', 'interestBasis', 'rateType', 'parTotalValue', 'startDate', 'endDate'];
    for (let index = 0; index < arr.length; index++) {
      const element = arr[index];
      if (this.props[element] != nextPorps[element]) {
        this.setState({
          fxData: [],
        });
        return;
      }
    }
    if (this.props['fixedRate'] != nextPorps['fixedRate']) {
      this.setState({
        fxData: [],
      });
      return;
    }
  };
  //此时是获取赎回日程中的内容
  getInfo = (callback) => {
    let { fxData } = this.state;
    let info;
    /**
         * 第一条数据的开始日期为【起息日】；
            前一条结束日期+1为第二条数据的开始日期；
            最后一条数据的结束日期为【到期日】；*/
    if (fxData && fxData.length) {
      if (moment(fxData[0].startDate).format('YYYY-MM-DD') != moment(this.props.startDate).format('YYYY-MM-DD')) {
        message.warning('第一条数据的开始日期必须为【起息日】');
        callback(false);
        return;
      }
      if (moment(fxData[fxData.length - 1].endDate).format('YYYY-MM-DD') != moment(this.props.endDate).format('YYYY-MM-DD')) {
        message.warning('最后一条数据的结束日期必须为【到期日】');
        callback(false);
        return;
      }
      for (let index = 0; index < fxData.length; index++) {
        const temp = fxData[index];
        if (temp.repaymentAmount < 0) {
          message.warning('还本金额不能为负数！');
          return;
        }
        if (index > 0) {
          if (
            moment(temp.startDate).format('YYYY-MM-DD') !=
            moment(fxData[index - 1].endDate)
              .add(1, 'day')
              .format('YYYY-MM-DD')
          ) {
            message.warning('前一条结束日期+1为第二条数据的开始日期');
            callback(false);
            return;
          }
        }
      }
      info = this.state.fxData;
    } else {
      info = [];
    }
    callback(info);
  };
  //表格数据
  renderTable = () => {
    let { loading } = this.props;
    let { fxData } = this.state;
    fxData.map((item, key) => {
      item.key = key + 1;
    });
    const columns = [
      {
        title: '期数',
        key: 'key',
        width: '8%',
      },
      {
        title: '开始日期',
        key: 'startDate',
        render: (text, record, index) => {
          return moment(text).format('YYYY-MM-DD');
        },
      },
      {
        title: '结束日期',
        key: 'endDate',
        render: (text, record, index) => {
          return moment(text).format('YYYY-MM-DD');
        },
      },
      {
        title: '付息金额',
        key: 'payInterestAmount',
        type: 'money',
      },
      {
        title: '还本金额',
        key: 'repaymentAmount',
        type: 'money',
      },
      {
        title: '剩余面额',
        key: 'spareFaceValue',
        type: 'money',
      },
      {
        title: '操作',
        key: 'operate',
        type: 'operate',
        width: 100,
        operates: [
          {
            title: '编辑',
            onClick: (record, index) => {
              this.edit(record);
            },
            rules: {
              disabled: { relation: 'and', items: [{ key: 'disable', value: [1], relation: ['='] }] },
            },
          },
          {
            title: '删除',
            rules: {
              disabled: { relation: 'and', items: [{ key: 'disable', value: [1], relation: ['='] }] },
            },
            onClick: (record, index) => {
              this.deletRow(record);
            },
          },
        ],
      },
    ];
    if (this.props.disableStatus) {
      //查看时不需要操作按钮
      if (columns && columns[columns.length - 1].key == 'operate') {
        columns.pop();
      }
    }
    columns.map((item) => {
      if (this.props.disableStatus) {
        if (item.key != 'key') {
          item.width = parseFloat(84 / (columns.length - 1)) + '%';
        }
      } else {
        if (item.key != 'operate' && item.key != 'key') {
          item.width = parseFloat(84 / (columns.length - 2)) + '%';
        }
      }
    });
    return (
      <div>
        <TableC
          columns={columns}
          loading={loading.effects['nonstandarmaintenanceNewM/calcFx'] == true}
          dataSource={fxData}
          rowKey='id'
          hidePage={true}
          scroll={{ x: '100%', y: '285px' }}
        />
      </div>
    );
  };
  add = () => {
    //新增付息日程列表
    if (this.validateParams()) {
      this.setState({
        isShow: true,
        showType: '1',
        rowData: { newAdd: true },
      });
    }
  };
  validateParams = () => {
    //点击“新增”按钮或“付息计算”按钮时，判断【发行规模】【付息频率】【计息基础】【起息日】【到期日】是否为空
    var arr = ['issueScale', 'interestRate', 'interestBasis', 'startDate', 'endDate', 'rateType', 'parTotalValue'];
    for (let index = 0; index < arr.length; index++) {
      const element = arr[index];
      if (this.props[element] == undefined) {
        message.warning('请输入发行规模、初始份额面值、利率类型、付息频率、计息基础、起息日和到期日。');
        return;
      }
    }
    if (this.props.rateType == 0 && this.props.fixedRate == undefined) {
      message.warning('请输入项目收益率（利率）。');
      return;
    }
    return '1';
  };
  //删除当前行
  deletRow = (value) => {
    let { fxData } = this.state;
    //删除后需要刷新表格
    const arr = fxData.filter((item) => item.id != value.id);
    let sum = this.props.parTotalValue;
    let sumHb = 0; //除去最后一行的还本金额之和
    arr.map((item, key) => {
      //自动计算最后一行还本金额
      if (key != arr.length - 1) {
        sumHb += item.repaymentAmount;
      } else {
        item.repaymentAmount = sum - sumHb;
      }
    });
    //计算剩余面额
    arr.map((item, key) => {
      if (key == 0) {
        item.spareFaceValue = sum - item.repaymentAmount;
      } else {
        item.spareFaceValue = arr[key - 1].spareFaceValue - item.repaymentAmount;
      }
    });
    //删除之后，后面数据的付息金额和剩余面额重新调整：
    //（2）后面行的【剩余面额】调整成当前行的剩余面额值。
    let qs;
    fxData.map((item, index) => {
      if (item.id == value.id) qs = index - 1;
    });
    arr.map((item, key, myArr) => {
      //计算后面行的付息金额
      if (key > qs) {
        //后面行的【付息金额】=当前行的付息金额 * 前一行的剩余面额 / 份额面值
        console.log(item);
        let payInterestAmount = item.oldPayInterestAmount; //当前行的付息金额是指初始值或者编辑后的值 不是取还本计算之后的
        item.payInterestAmount = ((payInterestAmount || 0) * (myArr[key - 1]['spareFaceValue'] || 0)) / this.props.parTotalValue;
      }
    });
    this.setState({
      fxData: [...arr],
    });
  };
  //编辑
  edit = (record) => {
    this.setState({
      startDate: moment(record.startDate),
      endDate: moment(record.endDate),
      rowData: record,
      isShow: true,
      showType: '2',
    });
  };

  //弹窗的 保存按钮
  onOk = () => {
    const {
      form: { validateFields },
      user: { currentUser },
    } = this.props;
    let { showType, rowData, fxData } = this.state;

    validateFields(['startDate', 'endDate', 'payInterestAmount', 'repaymentAmount'], (err, fieldsValue) => {
      if (err) return;
      if (this.props.parTotalValue < fieldsValue.repaymentAmount) {
        message.warning('还本金额不能大于份额面额!');
        return;
      }
      const newEditRow = {
        pid: this.props.id, //列表行的id
        userId: currentUser.userId,
        createDate: moment(),
        ...fieldsValue,
        repaymentAmount: fieldsValue.repaymentAmount || 0,
      };
      let arr = []; //临时存放日程列表数据
      if (showType == '1') {
        //新增
        newEditRow.id = uuid(32); //新增 给一个随机的id
        newEditRow.newAdd = rowData.newAdd; //手动新增的标志
        newEditRow.oldPayInterestAmount = fieldsValue.payInterestAmount || 0;
        (newEditRow.spareFaceValue = rowData.spareFaceValue || undefined), //编辑 额外加的
          (arr = JSON.parse(JSON.stringify(fxData)));
        arr.push(newEditRow);
      } else {
        //编辑
        newEditRow.id = rowData.id; //延用原有的id
        newEditRow.newAdd = rowData.newAdd; //手动新增的标志
        if (fieldsValue.payInterestAmount != rowData.payInterestAmount) {
          //如果付息金额变化，当前行有oldpay就取（属于后端返回的总的付息金额）； 没有就取输入框里的付息金额（属于手动输入）
          newEditRow.oldPayInterestAmount = rowData.oldPayInterestAmount != undefined ? rowData.oldPayInterestAmount : fieldsValue.payInterestAmount || 0; //付息金额变化则覆盖原来的付息金额
        } else newEditRow.oldPayInterestAmount = rowData.oldPayInterestAmount || 0; //原来的付息金额
        for (let i = 0; i < fxData.length; i++) {
          if (fxData[i].id == newEditRow.id) {
            arr.push(newEditRow);
          } else {
            arr.push(fxData[i]);
          }
        }
      }
      arr.sort(function (a, b) {
        //排序
        if (moment(a.startDate).format('YYYY-MM-DD') == moment(b.startDate).format('YYYY-MM-DD')) {
          moment(a.endDate).format('YYYY-MM-DD') > moment(b.endDate).format('YYYY-MM-DD') ? 1 : -1;
        }
        return moment(a.startDate).format('YYYY-MM-DD') > moment(b.startDate).format('YYYY-MM-DD') ? 1 : -1;
      });

      let sum = this.props.parTotalValue; //用份额面值计算
      let sumHb = 0; //除去最后一行的还本金额之和
      arr.map((item, key) => {
        //自动计算最后一行还本金额
        if (key != arr.length - 1) {
          sumHb += item.repaymentAmount;
        } else {
          item.repaymentAmount = sum - sumHb;
        }
      });

      //计算剩余面额
      arr.map((item, key) => {
        if (key == 0) {
          item.spareFaceValue = sum - item.repaymentAmount;
        } else {
          item.spareFaceValue = arr[key - 1].spareFaceValue - item.repaymentAmount;
        }
      });
      //还本后（编辑时，还本金额不为0），后面数据的付息金额和剩余面额重新调整：
      //（2）后面行的【剩余面额】调整成当前行的剩余面额值。
      let qs;
      arr.map((item, key, myArr) => {
        //计算后面行的付息金额
        if (newEditRow.id == item.id) {
          //编辑的行
          qs = key;
        }
        if (key > qs) {
          //后面行的【付息金额】=当前行的付息金额 * 前一行的剩余面额 / 份额面值
          let payInterestAmount = item.oldPayInterestAmount; //当前行的付息金额是指初始值或者编辑后的值 不是取还本计算之后的
          item.payInterestAmount = ((payInterestAmount || 0) * (myArr[key - 1]['spareFaceValue'] || 0)) / this.props.parTotalValue;
        }
      });
      this.setState({
        fxData: [...arr],
        isShow: false,
        rowData: {},
      });
    });
  };
  //弹窗的 取消按钮
  handleCancel = () => {
    this.setState({
      rowData: {},
      isShow: false,
    });
  };
  //新增编辑 弹窗
  showModal = () => {
    const { showType, isShow } = this.state;
    const modalProps = {
      visible: isShow,
      title: showType == '1' ? '新增' : '编辑',
      width: 600,
      height: 94,
      className: 'modalFx',
    };
    return (
      <ModalC {...modalProps} onOk={this.onOk} onCancel={this.handleCancel}>
        {this.renderForm()}
      </ModalC>
    );
  };
  //转化成标准格式比较日期大小 否则算出的比较大小结果会异常
  disabledStartDate = (startDate) => {
    //开始日期结束日期 要在起息日和到期日之间
    const endDate = this.props.form.getFieldsValue().endDate ? this.props.form.getFieldsValue().endDate.format('YYYYMMDD') : undefined; //结束日期

    const daoqiDate = moment(this.props.endDate).format('YYYYMMDD'); //到期日
    const qixiDate = moment(this.props.startDate).format('YYYYMMDD'); //起息日
    startDate = startDate ? startDate.format('YYYYMMDD') : undefined;
    if (!endDate) {
      //结束日期无数据时
      // if(this.state.rowData.newAdd){//手动新增的数据 这个规则
      //     return startDate > daoqiDate|| startDate < qixiDate
      // }else{//点击付息计算拿到的数据 编辑时候的规则
      // console.log(startDate,startDate > daoqiDate || startDate < qixiDate)
      return startDate > daoqiDate || startDate < qixiDate;
      // }
    } else {
      //
      // console.log(startDate )
      // if(this.state.rowData.newAdd){//手动新增的数据 这个规则
      //  return startDate > endDate || (startDate > moment(daoqiDate).add(1, 'd').format('YYYYMMDD') || startDate <qixiDate);
      // }else{//点击付息计算拿到的数据 编辑时候的规则
      return startDate > endDate || startDate > moment(daoqiDate).add(1, 'd').format('YYYYMMDD') || startDate < qixiDate;
      // }
    }
  };
  disabledEndDate = (endDate) => {
    //开始日期结束日期 要在起息日和到期日之间     //转化成标准格式比较日期大小 否则算出的比较大小结果会异常
    let startDate = this.props.form.getFieldsValue().startDate; //开始日期
    startDate = startDate ? startDate.format('YYYYMMDD') : undefined;
    const daoqiDate = moment(this.props.endDate).format('YYYYMMDD'); //到期日
    const qixiDate = moment(this.props.startDate).format('YYYYMMDD'); //起息日
    endDate = endDate.format('YYYYMMDD');
    if (!startDate) {
      // if(this.state.rowData.newAdd){//手动新增的数据 这个规则
      //     return endDate > daoqiDate || endDate <qixiDate
      // }else{//点击付息计算拿到的数据 编辑时候的规则
      return endDate > daoqiDate || endDate < qixiDate;
      // }
    } else {
      // if(this.state.rowData.newAdd){//手动新增的数据 这个规则
      //     return endDate < startDate || endDate > daoqiDate || endDate < qixiDate
      // }else{//点击付息计算拿到的数据 编辑时候的规则
      return endDate < startDate || endDate > daoqiDate || endDate < qixiDate;
      // }
    }
  };
  //弹窗开始日期结束日期 变更
  changeDate = (e, type) => {
    const {
      form: { setFieldsValue },
    } = this.props;
    this.setState(
      {
        [type]: e || undefined,
      },
      () => {
        if (this.state.startDate && this.state.endDate && this.state.showType == '2') {
          //取上一行的剩余面额
          let spareFaceValue = 0;
          let key = this.state.rowData.key - 2;
          if (key > -1) spareFaceValue = this.state.fxData[key]['spareFaceValue'];
          else spareFaceValue = this.props.parTotalValue;
          this.props.dispatch({
            //开始日期结束日期变更 查询付息金额
            type: 'nonstandarmaintenanceNewM/queryInterestpayment',
            payload: {
              startDate: this.state.startDate.format('YYYY-MM-DD'),
              endDate: this.state.endDate.format('YYYY-MM-DD'),
              interestBasis: this.props.interestBasis,
              interestRate: this.props.interestRate,
              parTotalValue: this.props.parTotalValue + '',
              // spareFaceValue:spareFaceValue+'',
              rateType: this.props.rateType,
              fixedRate: this.props.rateType == 0 ? this.props.fixedRate : undefined,
            },
            callback: (data) => {
              if (data) {
                //查询成功 设置付息金额
                this.state.rowData.oldPayInterestAmount = data.payInterestAmount || 0; //保存后端返回的付息金额 这个值是按照全部算的 所以需要乘上比例
                setFieldsValue({ payInterestAmount: ((data.payInterestAmount || 0) * spareFaceValue) / this.props.parTotalValue });
              }
            },
          });
        }
      },
    );
  };
  //新增编辑的表单
  renderForm = () => {
    const { rowData } = this.state;
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <div>
        <Row>
          <Col span={12}>
            <FormItem label='开始日期' {...FormItemLayout}>
              {getFieldDecorator('startDate', {
                initialValue: rowData.startDate ? moment(rowData.startDate) : undefined,
                rules: [
                  {
                    required: true,
                    message: '请选择开始日期',
                  },
                ],
              })(
                <DatePicker
                  placeholder='请选择'
                  style={{ width: '100%' }}
                  disabledDate={this.disabledStartDate}
                  // allowClear={false}
                  onChange={(e) => this.changeDate(e, 'startDate')}
                />,
              )}
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem label='结束日期' {...FormItemLayout}>
              {getFieldDecorator('endDate', {
                initialValue: rowData.endDate ? moment(rowData.endDate) : undefined,
                rules: [
                  {
                    required: true,
                    message: '请选择结束日期',
                  },
                ],
              })(
                <DatePicker
                  placeholder='请选择'
                  style={{ width: '100%' }}
                  disabledDate={this.disabledEndDate}
                  // allowClear={false}
                  onChange={(e) => this.changeDate(e, 'endDate')}
                />,
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <InputNumberC
              form={this.props.form} // form对象
              dataIndex={'payInterestAmount'}
              title={'付息金额'}
              unit='元'
              initialValue={rowData.payInterestAmount}
              splitStyle={true}
              min={0}
              precision={2}
            />
          </Col>
          <Col span={12}>
            <InputNumberC
              form={this.props.form} // form对象
              dataIndex={'repaymentAmount'}
              title={'还本金额'}
              unit='元'
              initialValue={rowData.repaymentAmount}
              splitStyle={true}
              min={0}
              precision={2}
            />
          </Col>
        </Row>
      </div>
    );
  };
  //付息计算
  calcFx = () => {
    if (this.validateParams()) {
      let data = {
        issueScale: this.props.issueScale,
        interestRate: this.props.interestRate,
        interestBasis: this.props.interestBasis,
        startDate: moment(this.props.startDate).format('YYYY-MM-DD'),
        endDate: moment(this.props.endDate).format('YYYY-MM-DD'),
        rateType: this.props.rateType,
        fixedRate: this.props.rateType == 0 ? this.props.fixedRate : undefined,
        parTotalValue: this.props.parTotalValue,
        id: this.props.id,
      };
      this.props.dispatch({
        //付息计算成功之后 覆盖手动新增编辑部分
        type: 'nonstandarmaintenanceNewM/calcFx',
        payload: {
          ...data,
        },
        callback: (data) => {
          if (data) {
            data.map((item) => {
              item.oldPayInterestAmount = item.payInterestAmount; //保存初始利息金额
            });
            this.setState({
              fxData: [...data],
            });
          }
        },
      });
    }
  };
  render() {
    const leftDom = () => {
      return (
        <Tooltip title={'仅支持利率类型为固定时计算，且，计算基础为初始份额面值'}>
          <QuestionCircleOutlined style={{ marginLeft: '5px' }} />
        </Tooltip>
      );
    };
    return (
      <div>
        <SecondHeaderC title='还本、付息日程' Left={leftDom()}></SecondHeaderC>
        {this.props.rateType != 2 && !this.props.disableStatus ? (
          <div className={style.btnFx} style={{ marginRight: '10px' }}>
            <PrimaryC title='付息计算' helper={'请必填发行规模、初始份额面值、利率类型、付息频率、计息基础、起息日和到期日'} onClick={this.calcFx} />
            <div>
              <PrimaryGhostC title='新增' helper={'请必填发行规模、初始份额面值、利率类型、付息频率、计息基础、起息日和到期日'} onClick={this.add} />
            </div>
          </div>
        ) : null}
        {this.state.isShow ? <div>{this.showModal()}</div> : null}
        <div style={{ marginBottom: '20px', width: '100%' }}>
          <InfoTipsC
            style={{ paddingLeft: '20px', width: '100%' }}
            Left='日期规则：第一条数据的开始日期为【起息日】；前一条结束日期+1为第二条数据的开始日期；最后一条数据的结束日期为【到期日】'
          ></InfoTipsC>
        </div>
        {this.renderTable()}
      </div>
    );
  }
}
export default connect(({ nonstandarmaintenanceNewM, loading, userM: user }) => ({
  nonstandarmaintenanceNewM,
  loading,
  user,
}))(Redemption);
